<template>
  <div class="lottery-bg-img min-h-screen w-full">
    <!-- 左上角红色齿轮按钮，务必放在最外层且不要被其他容器包裹 -->
    <el-button class="left-top-setting-btn" circle @click="openSettings">
      <el-icon><Setting /></el-icon>
    </el-button>
    <!-- 设置抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      direction="ltr"
      size="440px"
      :title="''"
      :with-header="true"
      :modal="true"
      :lock-scroll="true"
      custom-class="lottery-drawer-style lottery-drawer-red"
      :show-close="false"
    >
      <template #header>
        <div class="drawer-header-flex">
          <div class="drawer-title-animate breath-animate">抽奖设置</div>
          <button class="drawer-x-btn" type="button" aria-label="close" @click="closeSettings">
            <svg viewBox="0 0 1024 1024" class="drawer-x-icon" xmlns="http://www.w3.org/2000/svg" width="1.2em" height="1.2em"><path d="M512 464.6L777.4 199.2c12.5-12.5 32.8-12.5 45.3 0s12.5 32.8 0 45.3L557.4 509.9l265.3 265.3c12.5 12.5 12.5 32.8 0 45.3s-32.8 12.5-45.3 0L512 555.1 246.7 820.5c-12.5 12.5-32.8 12.5-45.3 0s-12.5-32.8 0-45.3l265.3-265.3-265.3-265.3c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0L512 464.6z" fill="#e53935"/></svg>
      </button>
    </div>
      </template>
      <el-form :model="settingsForm" label-width="100px" class="drawer-form-style drawer-form-wide">
        <el-form-item label="数字范围">
          <el-input-number v-model="settingsForm.numberMin" :min="0" :max="999" style="width: 120px;" />
          <span style="margin: 0 12px;">-</span>
          <el-input-number v-model="settingsForm.numberMax" :min="0" :max="999" style="width: 120px;" />
        </el-form-item>
        <el-form-item v-for="cfg in awardConfigs" :key="cfg.key" :label="cfg.label">
          <el-input-number v-model="settingsForm[cfg.limitKey]" :min="1" :max="99" style="width: 120px;" /> 位中奖人数
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="drawer-footer-btns">
          <el-button class="drawer-cancel-btn" @click="closeSettings">取消</el-button>
          <el-button class="drawer-save-btn" @click="saveSettings">保存</el-button>
      </div>
      </template>
    </el-drawer>
    <!-- 左侧中奖卡片，绝对定位 -->
    <div class="winner-card-glass absolute-left-card">
      <!-- 中奖区域标题只在无中奖记录时显示 -->
      <h2 v-if="winnerList.length === 0" class=" winner-marquee-wrap winner-title breath-animate">中奖区域</h2>
      <div v-else class="winner-marquee-wrap"
           @mouseenter="stopMarquee"
           @mouseleave="resumeMarquee">
        <div class="winner-marquee-inner"
             :style="{
               transform: `translateY(-${scrollIndex * 40}px)`,
               transition: isMarqueeTransition ? 'transform 0.6s cubic-bezier(0.4,0,0.2,1)' : 'none'
             }">
          <div v-for="(item, idx) in winnerList" :key="idx" class="winner-content">
            <span class="winner-msg-gradient"> 恭喜 </span>
            <span class="winner-msg-number">{{ extractNumber(item) }}</span>
            <span class="winner-msg-gradient"> 抽中 </span>
            <span class="winner-msg-award" :class="extractAwardClass(item)">{{ extractAward(item) }}</span>
    </div>
        </div>
      </div>

      <div v-if="flying && flyingNumber" :style="flyStyle" class="number-badge flying-badge">
        {{ flyingNumber }}
      </div>

      <!-- 奖项详细中奖信息区 -->
      <div class="winner-award-list">
        <div v-for="cfg in awardConfigs" :key="cfg.key" class="winner-award-item">
          <span class="award-title" :class="cfg.class">{{ cfg.label }}</span>
          <span class="award-remaining">剩余{{ getRemainingSlots(cfg.value) }}人</span>
          <div class="award-number-list" :class="cfg.class">
            <template v-if="!awardWinners[cfg.key] || awardWinners[cfg.key].length === 0">
              <span class="no-winner">暂无中奖者</span>
            </template>
            <span v-for="num in (awardWinners[cfg.key] || [])" :key="num" class="number-badge">{{ num }}</span>
      </div>
    </div>
      </div>
      </div>
    <!-- 主内容始终居中 -->
    <div class="lottery-main-content-center">
      <div class="lucky-title-space"></div>
      <img src="/xinyunchoujiang.png" alt="幸运抽奖" class="lucky-title-img breath-animate" />
      <div class="rects-row">
        <div class="rect-img rect-num-bg">
          <div class="roller">
            <div class="roller-inner">
              <div :class="['roller-num', 'rect-num1', !rolling[0] ? 'roller-num-breath breath-animate' : '']" :style="{
                color: '#ff0000',
                background: 'none',
                WebkitBackgroundClip: 'unset',
                WebkitTextFillColor: 'unset',
                backgroundClip: 'unset',
                fontSize: '5.2rem',
                fontWeight: 'bold',
              }">{{ numbers[0] }}</div>
            </div>
          </div>
        </div>
        <div class="rect-img rect-num-bg">
          <div class="roller">
            <div class="roller-inner">
              <div :class="['roller-num', 'rect-num2', !rolling[1] ? 'roller-num-breath breath-animate' : '']" :style="{
                color: '#ff0000',
                background: 'none',
                WebkitBackgroundClip: 'unset',
                WebkitTextFillColor: 'unset',
                backgroundClip: 'unset',
                fontSize: '5.2rem',
                fontWeight: 'bold',
              }">{{ numbers[1] }}</div>
            </div>
          </div>
        </div>
        <div class="rect-img rect-num-bg">
          <div class="roller">
            <div class="roller-inner">
              <div :class="['roller-num', 'rect-num3', !rolling[2] ? 'roller-num-breath breath-animate' : '']" :style="{
                color: '#ff0000',
                background: 'none',
                WebkitBackgroundClip: 'unset',
                WebkitTextFillColor: 'unset',
                backgroundClip: 'unset',
                fontSize: '5.2rem',
                fontWeight: 'bold',
              }">{{ numbers[2] }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 右下角开始抽奖按钮 -->
    <div class="fixed-lottery-btn-wrap">
      <img :src="lotteryBtnImg" alt="开始抽奖按钮" class="fixed-lottery-btn" @click="startOrStopLottery" :class="[{ 'btn-loading': isBtnLoading }, !isBtnLoading ? 'lottery-btn-breath breath-animate' : '']" :style="isBtnLoading ? 'pointer-events:none;opacity:0.6;' : ''" />
      <div v-if="isBtnLoading" class="btn-loading-mask">
        <span class="btn-loading-spinner"></span>
      </div>
    </div>
    <!-- 底部奖项选择栏 -->
    <div class="bottom-award-select-bar">
      <div class="award-bg-select-wrapper">
        <img src="/juxin3.png" alt="奖项装饰" class="award-bg-img" />
        <el-select v-model="awardLevel" class="award-select-on-bg" placeholder="请选择奖项" size="large">
          <el-option
            v-for="cfg in awardConfigs"
            :key="cfg.value"
            :label="`${cfg.label} (剩余${getRemainingSlots(cfg.value)}人)`"
            :value="cfg.value"
            :disabled="!hasRemainingSlots(cfg.value)"
          />
        </el-select>
      </div>
    </div>
    <!-- 右上角装饰和按钮 -->
    <div class="top-right-reset">
        <img src="/juxin3.png" alt="reset-bg" class="reset-bg-img" />
        <el-button type="warning" class="reset-btn" size="large" @click="resetLottery">
          <i class="el-icon-refresh"></i>
          重置抽奖
        </el-button>
        <!-- 临时调试按钮 -->
        <!-- <el-button type="info" class="debug-btn" size="small" @click="debugCurrentState" style="margin-left: 10px;">
          调试状态
        </el-button> -->
    </div>
  </div>
</template>

<script setup>
// --------------------
// 导入依赖
// --------------------
import { ref, onUnmounted, nextTick, onMounted, watch } from 'vue';
import { ElButton, ElSelect, ElOption, ElDrawer, ElForm, ElFormItem, ElInput, ElInputNumber, ElMessage } from 'element-plus';
import { Setting } from '@element-plus/icons-vue';
import * as confetti from 'canvas-confetti';
import { lotteryApi } from '../api/lottery.js';
window.confetti = confetti;

// --------------------
// 后端数据状态
// --------------------
const lotterySettings = ref({
  prize: null,
  settings: []
});
const currentSetting = ref(null);
const currentPrize = ref(null);

// --------------------
// 中奖号码动画相关状态
// --------------------
const flyingNumber = ref(null); // 当前飞行的号码
const flying = ref(false);      // 是否正在飞行
const flyStyle = ref({});       // 飞行号码牌的样式

// --------------------
// 主要状态和数据
// --------------------
const awardLevel = ref('特等奖'); // 当前奖项
const isRunning = ref(false);     // 是否正在滚动
const isBtnLoading = ref(false);  // 按钮loading
const lotteryBtnImg = ref('/kaishichoujiang.png');
const numbers = ref([0, 0, 0]);   // 当前显示的3位数字
const gradients = ref([
  'linear-gradient(90deg, #ff3cac, #784ba0)',
  'linear-gradient(90deg, #42e695, #3bb2b8)',
  'linear-gradient(90deg, #f7971e, #ffd200)'
]);
const rolling = ref([false, false, false]); // 每个数字是否在滚动
const timers = [null, null, null];           // 每个数字的定时器
const targetNumbers = ref([0, 0, 0]); // 停止后要显示的中奖号码三位

// --------------------
// 中奖号码列表（各奖项）
// --------------------
const awardWinners = ref({
  special: [],
  first: [],
  second: [],
  third: [],
  lucky: []
});

// --------------------
// 滚动中奖信息列表
// --------------------
const winnerList = ref([]); // 每次中奖后push一条信息
const scrollIndex = ref(0);
const isMarqueePaused = ref(false);
const isMarqueeTransition = ref(true);
let scrollTimer = null;

// --------------------
// 奖项配置（动态渲染用）
// --------------------
const awardConfigs = [
  { key: 'special', label: '特等奖', class: 'special', value: '特等奖', limitKey: 'specialLimit' },
  { key: 'first', label: '一等奖', class: 'first', value: '一等奖', limitKey: 'firstLimit' },
  { key: 'second', label: '二等奖', class: 'second', value: '二等奖', limitKey: 'secondLimit' },
  { key: 'third', label: '三等奖', class: 'third', value: '三等奖', limitKey: 'thirdLimit' },
  { key: 'lucky', label: '幸运奖', class: 'lucky', value: '幸运奖', limitKey: 'luckyLimit' }
];

// --------------------
// 设置抽屉相关
// --------------------
const drawerVisible = ref(false);
const settingsForm = ref({
  numberMin: 0,
  numberMax: 999,
  awardSpecial: '特等奖',
  awardFirst: '一等奖',
  awardSecond: '二等奖',
  awardThird: '三等奖',
  awardLucky: '幸运奖',
  specialLimit: 1,
  firstLimit: 2,
  secondLimit: 3,
  thirdLimit: 5,
  luckyLimit: 10,
});

// --------------------
// API调用方法
// --------------------
// 获取抽奖设置
async function fetchLotterySettings() {
  try {
    const response = await lotteryApi.getSettings();
    console.log('📥 获取设置API响应:', response.data);

    if (response.data.success) {
      lotterySettings.value = response.data;
      // 设置默认值
      if (response.data.prizes && response.data.prizes.length > 0) {
        currentPrize.value = response.data.prizes[0];
        settingsForm.value.numberMin = parseInt(currentPrize.value.minNumber);
        settingsForm.value.numberMax = parseInt(currentPrize.value.maxNumber);
        console.log('✅ 设置奖品信息:', currentPrize.value);
      } else {
        console.log('⚠️ 没有奖品数据');
      }

      if (response.data.settings && response.data.settings.length > 0) {
        currentSetting.value = response.data.settings[0];
        // 更新奖项配置
        updateAwardConfigs(response.data.settings);
        console.log('✅ 设置配置信息:', currentSetting.value);
      } else {
        console.log('⚠️ 没有设置数据');
      }
    }
  } catch (error) {
    console.error('获取抽奖设置失败:', error);
    // 不显示错误消息，使用默认值
    console.log('使用默认抽奖设置');
  }
}

// 获取中奖记录
async function fetchWinners() {
  try {
    const response = await lotteryApi.getWinners();
    if (response.data.success) {
      awardWinners.value = response.data.awardWinners || {
        special: [],
        first: [],
        second: [],
        third: [],
        lucky: []
      };

      // 根据中奖记录重新构建跑马灯列表
      rebuildWinnerList();
    }
  } catch (error) {
    console.error('获取中奖记录失败:', error);
    // 确保即使API失败也有默认值
    awardWinners.value = {
      special: [],
      first: [],
      second: [],
      third: [],
      lucky: []
    };
    console.log('使用默认中奖记录');
    // 清空跑马灯列表
    winnerList.value = [];
  }
}

// 开始抽奖
async function startLottery() {
  try {
    // 根据当前奖项获取对应的设置ID
    const currentAwardCode = getAwardKeyByAwardName(awardLevel.value);
    const targetSetting = lotterySettings.value.settings?.find(setting => setting.awardCode === currentAwardCode);

    console.log('🔧 抽奖请求参数:');
    console.log('  - currentPrize.value:', currentPrize.value);
    console.log('  - currentSetting.value:', currentSetting.value);
    console.log('  - 当前奖项:', awardLevel.value);
    console.log('  - 当前奖项代码:', currentAwardCode);
    console.log('  - 目标设置:', targetSetting);

    const requestData = {
      userId: 1, // 可以根据实际用户ID调整
      prizeId: currentPrize.value?.id || 1,
      settingId: targetSetting?.id || 1,
      awardLevel: awardLevel.value
    };

    console.log('📤 发送请求数据:', requestData);

    const response = await lotteryApi.startLottery(requestData);

    if (response.data.success) {
      return {
        luckyNumber: response.data.luckyNumber,
        awardCode: response.data.awardCode,
        awardLevel: response.data.awardLevel
      };
    } else {
      ElMessage.error(response.data.message || '抽奖失败');
      return null;
    }
  } catch (error) {
    console.error('抽奖失败:', error);
    // 模拟抽奖结果（当API不可用时）
    const min = settingsForm.value.numberMin || 0;
    const max = settingsForm.value.numberMax || 999;
    const luckyNumber = Math.floor(Math.random() * (max - min + 1)) + min;
    const luckyNumberStr = luckyNumber.toString().padStart(3, '0');

    return {
      luckyNumber: luckyNumberStr,
      awardCode: awardLevel.value,
      awardLevel: awardLevel.value
    };
  }
}

// 重置抽奖
async function resetLottery() {
  try {
    const response = await lotteryApi.resetLottery();
    if (response.data.success) {
      // 清空本地中奖记录
      awardWinners.value = {
        special: [],
        first: [],
        second: [],
        third: [],
        lucky: []
      };
      winnerList.value = [];

      // 清空本地状态
      const min = Math.max(0, settingsForm.value.numberMin);
      numbers.value = [min, min, min];
      rolling.value = [false, false, false];
      isRunning.value = false;
      isBtnLoading.value = false;
      lotteryBtnImg.value = '/kaishichoujiang.png';
      scrollIndex.value = 0;

      // 清除所有定时器
      for (let i = 0; i < 3; i++) {
        if (timers[i]) {
          clearInterval(timers[i]);
          timers[i] = null;
        }
      }
      // 清除滚动定时器
      if (scrollTimer) {
        clearInterval(scrollTimer);
        scrollTimer = null;
      }
      // 重新启动滚动动画
      startMarquee();

      ElMessage.success('抽奖已重置');
    }
  } catch (error) {
    console.error('重置失败:', error);
    // 即使API失败也执行本地重置
    awardWinners.value = {
      special: [],
      first: [],
      second: [],
      third: [],
      lucky: []
    };
    winnerList.value = [];

    // 清空本地状态
    const min = Math.max(0, settingsForm.value.numberMin);
    numbers.value = [min, min, min];
    rolling.value = [false, false, false];
    isRunning.value = false;
    isBtnLoading.value = false;
    lotteryBtnImg.value = '/kaishichoujiang.png';
    scrollIndex.value = 0;

    // 清除所有定时器
    for (let i = 0; i < 3; i++) {
      if (timers[i]) {
        clearInterval(timers[i]);
        timers[i] = null;
      }
    }
    // 清除滚动定时器
    if (scrollTimer) {
      clearInterval(scrollTimer);
      scrollTimer = null;
    }
    // 重新启动滚动动画
    startMarquee();

    ElMessage.success('抽奖已重置');
  }
}

// 保存设置
async function saveSettings() {
  try {
    // 构建保存请求
    const saveRequest = {
      prize: {
        id: currentPrize.value?.id,
        minNumber: settingsForm.value.numberMin.toString().padStart(3, '0'),
        maxNumber: settingsForm.value.numberMax.toString().padStart(3, '0')
      },
      settings: lotterySettings.value.settings.map(setting => ({
        ...setting,
        totalWinners: settingsForm.value[getLimitKeyByAwardCode(setting.awardCode)]
      }))
    };

    const response = await lotteryApi.saveSettings(saveRequest);
    if (response.data.success) {
      ElMessage.success('设置保存成功');
      closeSettings();
      // 重新获取设置
      await fetchLotterySettings();
      } else {
      ElMessage.error(response.data.message || '保存失败');
      }
    } catch (error) {
    console.error('保存设置失败:', error);
    ElMessage.error('保存设置失败');
  }
}

// --------------------
// 工具函数
// --------------------
// 生成随机渐变色
function randomGradient() {
  const colors = [
    '#ff3cac', '#784ba0', '#2b86c5', '#42e695', '#f9d423', '#ff6e7f', '#f7971e', '#ffd200', '#21d4fd', '#b721ff'
  ];
  const pick = () => colors[Math.floor(Math.random() * colors.length)];
  return `linear-gradient(90deg, ${pick()}, ${pick()}, ${pick()})`;
}

// 提取中奖号码
function extractNumber(msg) {
  const m = msg.match(/恭喜\s+(\d+)\s+抽中/);
  return m ? m[1] : '';
}

// 提取奖项名
function extractAward(msg) {
  const m = msg.match(/抽中(.+)$/);
  return m ? m[1] : '';
}

// 提取奖项名对应的class
function extractAwardClass(msg) {
  const award = extractAward(msg);
  if (award.includes('特等奖')) return 'special';
  if (award.includes('一等奖')) return 'first';
  if (award.includes('二等奖')) return 'second';
  if (award.includes('三等奖')) return 'third';
  if (award.includes('幸运奖')) return 'lucky';
  return '';
}

// 根据奖项标识码获取奖项Key
function getAwardKeyByCode(awardCode) {
  if (!awardCode) return 'other';

  switch (awardCode.toLowerCase()) {
    case 'special': return 'special';
    case 'first': return 'first';
    case 'second': return 'second';
    case 'third': return 'third';
    case 'lucky': return 'lucky';
    default: return 'other';
  }
}

// 根据中文奖项名称获取奖项Key
function getAwardKeyByAwardName(awardName) {
  switch (awardName) {
    case '特等奖': return 'special';
    case '一等奖': return 'first';
    case '二等奖': return 'second';
    case '三等奖': return 'third';
    case '幸运奖': return 'lucky';
    default: return 'other';
  }
}

// 根据奖项标识码获取限制Key
function getLimitKeyByAwardCode(awardCode) {
  switch (awardCode.toLowerCase()) {
    case 'special': return 'specialLimit';
    case 'first': return 'firstLimit';
    case 'second': return 'secondLimit';
    case 'third': return 'thirdLimit';
    case 'lucky': return 'luckyLimit';
    default: return 'otherLimit';
  }
}

// 根据中文奖项名称获取限制Key
function getLimitKeyByAwardName(awardName) {
  switch (awardName) {
    case '特等奖': return 'specialLimit';
    case '一等奖': return 'firstLimit';
    case '二等奖': return 'secondLimit';
    case '三等奖': return 'thirdLimit';
    case '幸运奖': return 'luckyLimit';
    default: return 'otherLimit';
  }
}

// 更新奖项配置
function updateAwardConfigs(settings) {
  console.log('🔄 更新奖项配置:', settings);
  settings.forEach(setting => {
    const limitKey = getLimitKeyByAwardCode(setting.awardCode);
    if (limitKey !== 'otherLimit') {
      settingsForm.value[limitKey] = setting.totalWinners;
      console.log(`  - ${setting.prizeName} (${setting.awardCode}): 限制Key=${limitKey}, 限制值=${setting.totalWinners}`);
    }
  });
}

// 检查奖项是否还有剩余名额
function hasRemainingSlots(awardLevel) {
  const awardKey = getAwardKeyByAwardName(awardLevel);
  const limit = settingsForm.value[getLimitKeyByAwardName(awardLevel)] || 0;
  const currentWinners = awardWinners.value[awardKey] || [];
  return currentWinners.length < limit;
}

// 获取奖项剩余名额数量
function getRemainingSlots(awardLevel) {
  const awardKey = getAwardKeyByAwardName(awardLevel);
  const limitKey = getLimitKeyByAwardName(awardLevel);
  const limit = settingsForm.value[limitKey] || 0;
  const currentWinners = awardWinners.value[awardKey] || [];
  const remaining = Math.max(0, limit - currentWinners.length);

  // 调试信息
  console.log(`奖项: ${awardLevel}, 奖项Key: ${awardKey}, 限制Key: ${limitKey}, 限制: ${limit}, 当前中奖者: ${currentWinners.length}, 剩余: ${remaining}`);

  return remaining;
}

// 根据中奖记录重新构建跑马灯列表
function rebuildWinnerList() {
  winnerList.value = [];

  // 奖项映射
  const awardMap = {
    special: '特等奖',
    first: '一等奖',
    second: '二等奖',
    third: '三等奖',
    lucky: '幸运奖'
  };

  // 遍历所有奖项的中奖记录
  Object.keys(awardWinners.value).forEach(awardKey => {
    const awardName = awardMap[awardKey];
    const winners = awardWinners.value[awardKey] || [];

    // 为每个中奖号码创建消息
    winners.forEach(winnerNumber => {
      const msg = `恭喜 ${winnerNumber} 抽中${awardName}`;
      winnerList.value.push(msg);
    });
  });

  console.log('🔄 重新构建跑马灯列表:', winnerList.value);
}

// 更新中奖记录（在动画完成后调用）
function updateWinnerRecord(lotteryResult) {
  // 更新中奖记录
  const awardKey = getAwardKeyByCode(lotteryResult.awardCode) || getAwardKeyByAwardName(lotteryResult.awardLevel);
  if (awardWinners.value[awardKey]) {
    awardWinners.value[awardKey].push(lotteryResult.luckyNumber);
  }

  // 添加到滚动信息
  const msg = `恭喜 ${lotteryResult.luckyNumber} 抽中${lotteryResult.awardLevel}`;
  winnerList.value.push(msg);
  console.log('📝 添加中奖信息到跑马灯:', msg);
  console.log('📊 当前跑马灯列表:', winnerList.value);
}

// 强制停止所有动画
function forceStopAllAnimations() {
  // 停止所有数字滚动
  for (let i = 0; i < 3; i++) {
    if (timers[i]) {
      clearInterval(timers[i]);
      timers[i] = null;
    }
    rolling.value[i] = false;
  }

  // 重置状态
  isRunning.value = false;
  isBtnLoading.value = false;
  lotteryBtnImg.value = '/kaishichoujiang.png';

  // 清除滚动定时器
  if (scrollTimer) {
    clearInterval(scrollTimer);
    scrollTimer = null;
  }
}

// 测试奖项映射函数
function testAwardMapping() {
  const testAwards = ['特等奖', '一等奖', '二等奖', '三等奖', '幸运奖'];
  console.log('=== 测试奖项映射 ===');
  testAwards.forEach(award => {
    const awardKey = getAwardKeyByAwardName(award);
    const limitKey = getLimitKeyByAwardName(award);
    console.log(`${award} -> 奖项Key: ${awardKey}, 限制Key: ${limitKey}`);
  });
  console.log('=== 测试完成 ===');
}

// 调试当前状态
function debugCurrentState() {
  console.log('=== 当前状态调试 ===');
  console.log('当前选择的奖项:', awardLevel.value);
  console.log('当前所有中奖记录:', JSON.stringify(awardWinners.value, null, 2));
  console.log('当前设置:', JSON.stringify(settingsForm.value, null, 2));

  const testAwards = ['特等奖', '一等奖', '二等奖', '三等奖', '幸运奖'];
  testAwards.forEach(award => {
    const awardKey = getAwardKeyByAwardName(award);
    const limitKey = getLimitKeyByAwardName(award);
    const limit = settingsForm.value[limitKey] || 0;
    const currentWinners = awardWinners.value[awardKey] || [];
    const remaining = Math.max(0, limit - currentWinners.length);

    console.log(`${award}: 奖项Key=${awardKey}, 限制Key=${limitKey}, 限制=${limit}, 当前中奖者=${currentWinners.length}, 剩余=${remaining}`);
  });
  console.log('=== 调试完成 ===');
}

// --------------------
// 主要交互逻辑
// --------------------
// 开始/停止抽奖
async function startOrStopLottery() {
  if (isBtnLoading.value) return; // 防抖

  if (!isRunning.value) {
    // 在开始抽奖前检查人数是否达到上限
    console.log('=== 开始抽奖检查 ===');
    console.log('当前选择的奖项:', awardLevel.value);
    console.log('奖项类型:', typeof awardLevel.value);

    const currentAwardKey = getAwardKeyByAwardName(awardLevel.value);
    const limitKey = getLimitKeyByAwardName(awardLevel.value);
    const currentLimit = settingsForm.value[limitKey] || 0;
    const currentWinners = awardWinners.value[currentAwardKey] || [];

    // 验证数据正确性
    console.log(`🔍 数据验证:`);
    console.log(`  - 奖项名称: "${awardLevel.value}"`);
    console.log(`  - 奖项Key: "${currentAwardKey}"`);
    console.log(`  - 限制Key: "${limitKey}"`);
    console.log(`  - 限制值: ${currentLimit}`);
    console.log(`  - 当前中奖者数组:`, currentWinners);
    console.log(`  - 中奖者数量: ${currentWinners.length}`);
    console.log(`  - 剩余名额: ${Math.max(0, currentLimit - currentWinners.length)}`);

    console.log(`检查奖项: ${awardLevel.value}, 奖项Key: ${currentAwardKey}, 限制: ${currentLimit}, 当前中奖者: ${currentWinners.length}`);
    console.log('当前所有中奖记录:', JSON.stringify(awardWinners.value, null, 2));
    console.log(`限制Key: ${getLimitKeyByAwardName(awardLevel.value)}, 限制值: ${settingsForm.value[getLimitKeyByAwardName(awardLevel.value)]}`);
    console.log(`当前奖项中奖者数组:`, currentWinners);
    console.log('=== 检查完成 ===');

    // 直接比较数值
    const isOverLimit = currentWinners.length >= currentLimit;
    console.log(`🔍 最终检查结果: ${currentWinners.length} >= ${currentLimit} = ${isOverLimit}`);

    if (isOverLimit) {
      console.log(`❌ 检查失败: 当前中奖者(${currentWinners.length}) >= 限制(${currentLimit})`);
      ElMessage.warning(`${awardLevel.value}人数已达上限（${currentLimit}人），请选择其他奖项或重置抽奖`);
      // 强制停止所有动画
      forceStopAllAnimations();
      return;
    } else {
      console.log(`✅ 检查通过: 当前中奖者(${currentWinners.length}) < 限制(${currentLimit})`);
    }

    // 开始滚动
    isRunning.value = true;
    lotteryBtnImg.value = '/tintzhichoujiang.png';
    rolling.value = [true, true, true];
    for (let i = 0; i < 3; i++) {
      if (timers[i]) clearInterval(timers[i]);
      timers[i] = setInterval(() => {
        numbers.value[i] = (numbers.value[i] + 1) % 10;
        gradients.value[i] = randomGradient();
      }, 60);
    }
  } else {
    // 停止滚动并调用后端抽奖
    isRunning.value = false;
    lotteryBtnImg.value = '/kaishichoujiang.png';
    isBtnLoading.value = true;

        try {
      const lotteryResult = await startLottery();
      if (lotteryResult) {
        const str = lotteryResult.luckyNumber.toString().padStart(3, '0');
        targetNumbers.value = [Number(str[0]), Number(str[1]), Number(str[2])];
        stopOneByOne(0, () => {
          // 数字停止后，不立即更新记录，等待飞入动画完成
          isBtnLoading.value = false;
        }, lotteryResult);
      } else {
        isBtnLoading.value = false;
        isRunning.value = true;
        lotteryBtnImg.value = '/tintzhichoujiang.png';
      }
  } catch (error) {
      isBtnLoading.value = false;
      isRunning.value = true;
      lotteryBtnImg.value = '/tintzhichoujiang.png';
    }
  }
}

// 依次停止数字滚动，带回调
function stopOneByOne(idx, cb, lotteryResult) {
  if (idx > 2) {
    if (cb) cb();
    return;
  }
  setTimeout(() => {
    rolling.value[idx] = false;
    if (timers[idx]) {
      clearInterval(timers[idx]);
      timers[idx] = null;
    }
    // 停止时直接显示中奖号码的该位
    numbers.value[idx] = targetNumbers.value[idx];
    if (idx === 2) {
      // 后续中奖逻辑
      const currentNumber = numbers.value.join('');
      const awardMap = {
        '特等奖': { key: 'special', selector: '.award-number-list.special' },
        '一等奖': { key: 'first', selector: '.award-number-list.first' },
        '二等奖': { key: 'second', selector: '.award-number-list.second' },
        '三等奖': { key: 'third', selector: '.award-number-list.third' },
        '幸运奖': { key: 'lucky', selector: '.award-number-list.lucky' }
      };
      const map = awardMap[awardLevel.value];
      if (map) {
        flyToAward(currentNumber, map.key, map.selector, lotteryResult);
      }
      window.confetti.default({ particleCount: 200, spread: 180, zIndex: 9999 });
      setTimeout(() => {
        window.confetti.default({ particleCount: 200, spread: 180, zIndex: 9999 });
      }, 500);
      setTimeout(() => {
        window.confetti.default({ particleCount: 200, spread: 180, zIndex: 9999 });
      }, 1000);
      if (cb) cb();
    } else {
      stopOneByOne(idx + 1, cb, lotteryResult);
    }
  }, 1000);
}

// 中奖号码飞入动画
function flyToAward(currentNumber, awardKey, awardClass, lotteryResult) {
  flyingNumber.value = currentNumber;
  flying.value = true;
  flyStyle.value = {}; // 先清空，确保每次动画都从中心起点
  nextTick().then(() => {
    const badgeW = 120, badgeH = 60;
    const startLeft = window.innerWidth / 2 - badgeW / 2;
    const startTop = window.innerHeight / 2 - badgeH / 2;
    const end = document.querySelector(awardClass).getBoundingClientRect();
    flyStyle.value = {
      position: 'fixed',
      left: `${startLeft}px`,
      top: `${startTop}px`,
      width: `${badgeW}px`,
      height: `${badgeH}px`,
      fontSize: '2.2rem',
      transition: 'all 1.5s cubic-bezier(0.4,0,0.2,1)',
      zIndex: 99999
    };
    nextTick().then(() => {
      setTimeout(() => {
        flyStyle.value = {
          ...flyStyle.value,
          left: `${end.left + 100}px`,
          top: `${end.top - 10}px`,
          width: '48px',
          height: '32px',
          fontSize: '1.2rem'
        };
      }, 50);
      setTimeout(async () => {
        flying.value = false;
        flyingNumber.value = null;
        // 飞入动画完成后，更新中奖记录并刷新抽奖区域
        if (lotteryResult) {
          updateWinnerRecord(lotteryResult);
          await fetchWinners();
        }
      }, 1550);
    });
  });
}

// --------------------
// 滚动中奖信息动画
// --------------------
function startMarquee() {
  if (scrollTimer) clearInterval(scrollTimer);
  scrollTimer = setInterval(() => {
    if (!isMarqueePaused.value && winnerList.value.length > 1) {
      if (scrollIndex.value < winnerList.value.length - 1) {
        isMarqueeTransition.value = true;
        scrollIndex.value++;
      } else {
        // 到最后一条，瞬间切回第一条，不立即滚动
        isMarqueeTransition.value = false;
        scrollIndex.value = 0;
      }
    }
  }, 1800);
}
function stopMarquee() { isMarqueePaused.value = true; }
function resumeMarquee() { isMarqueePaused.value = false; }

// --------------------
// 设置抽屉相关
// --------------------


function openSettings() {
  drawerVisible.value = true;
  // 打开设置时获取最新数据
  fetchLotterySettings();
}

function closeSettings() { drawerVisible.value = false; }

// --------------------
// 生命周期
// --------------------
onMounted(async () => {
  // 组件挂载时获取初始数据
  try {
    await fetchLotterySettings();
    await fetchWinners();
  } catch (error) {
    console.error('初始化数据失败:', error);
    // 确保有默认值
    awardWinners.value = {
      special: [],
      first: [],
      second: [],
      third: [],
      lucky: []
    };
    // 清空跑马灯列表
    winnerList.value = [];
  }
  startMarquee();

  // 测试奖项映射
  testAwardMapping();
});

// 监听奖项选择变化
watch(awardLevel, (newValue, oldValue) => {
  console.log(`奖项选择变化: ${oldValue} -> ${newValue}`);
  console.log(`新奖项的剩余名额: ${getRemainingSlots(newValue)}`);
});

onUnmounted(() => {
  for (let i = 0; i < 3; i++) {
    if (timers[i]) clearInterval(timers[i]);
  }
  if (scrollTimer) clearInterval(scrollTimer);
});
</script>

<style scoped>
.lottery-bg-img {
  position: relative;
  min-height: 100vh;
  width: 100vw;
  background: url('/beijing2x.png') center center/cover no-repeat;
}
.absolute-left-card {
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  z-index: 10;
  margin-top: 10px; /* 向上偏移，为顶部留出空间 */
}
.lottery-main-content-center {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 320px;
  margin: 0 auto;
  padding-top: 20px;
}
.winner-card-glass {
  min-width: 480px;
  max-width: 480px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.winner-title {
  font-size: 1.6rem;
  font-weight: bold;
  color: #b91c1c;
  letter-spacing: 2px;
  text-shadow: 0 2px 12px #ffb3b3, 0 0 24px #f7f4f4, 0 0 2px #fff;
}

.winner-content {
  font-size: 1.2rem;
  color: #FFFFFF;
  text-align: center;
}
.lucky-title-space {
  width: 100%;
  height: 8vh;
}
.lucky-title-img {
  width: 60vw;
  max-width: 800px;
  min-width: 220px;
  display: block;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 32px;
  border-radius: 24px;
  transition: transform 0.2s;
  animation: lucky-title-bounce-glow 1.8s cubic-bezier(0.4,0,0.2,1) infinite alternate;
  /* 不设置边框，只用阴影呼吸效果 */
}
.lucky-title-img:hover {
  transform: scale(1.03) rotate(-1deg);
}
@keyframes lucky-title-bounce-glow {
  0% {
    transform: scale(1) translateY(0);
  }
  50% {
    transform: scale(1.05) translateY(-10px) rotate(-1deg);
  }
  100% {
    transform: scale(1) translateY(0);
  }
}
.rects-row {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  gap: 80px;
  margin-top: 80px;
}
.rect-img {
  width: 160px;
  height: 160px;
  object-fit: contain;
  border-radius: 24px;
  box-shadow: 0 4px 24px #eab7a6aa;
  background: transparent;
  position: relative;
  overflow: hidden;
}
.rect-img.rect-num-bg {
  background: url('/zhengfangxjuxing.png') center center/cover no-repeat;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}
.rect-num {
  font-size: 4.2rem;
  font-weight: bold;
  background: linear-gradient(270deg, #ff3cac, #784ba0, #2b86c5, #42e695, #f9d423, #ff3cac, #ff6e7f, #f7971e, #ffd200, #21d4fd, #b721ff, #ff3cac);
  background-size: 2000% 2000%;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  text-fill-color: transparent;
  filter: drop-shadow(0 2px 8px #ffecb366);
  letter-spacing: 2px;
  text-shadow: 0 2px 8px #b91c1c99, 0 1px 0 #fff;
  animation: rainbow-gradient-move 1.2s linear infinite alternate;
}
.fixed-lottery-btn-wrap {
  position: fixed;
  right: 56px;
  bottom: 56px;
  z-index: 100;
  width: 180px;
  height: 180px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.fixed-lottery-btn {
  width: 180px;
  height: 180px;
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}
.fixed-lottery-btn:hover {
  transform: scale(1.08) rotate(-2deg);
}
.btn-loading-mask {
  position: absolute;
  left: 0; top: 0; right: 0; bottom: 0;
  background: rgba(255,255,255,0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  pointer-events: none;
}
.btn-loading-spinner {
  width: 48px;
  height: 48px;
  border: 5px solid #fff;
  border-top: 5px solid #ff0000;
  border-radius: 50%;
  animation: btn-spin 1s linear infinite;
}
@keyframes btn-spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
.top-right-reset {
  position: fixed;
  top: 32px;
  right: 48px;
  z-index: 20;
  display: flex;
  align-items: center;
}
.reset-bg-img {
  width: 165px;
  height: 81px;
  object-fit: contain;
  border-radius: 18px;
  box-shadow: 0 2px 12px #eab7a6aa;
}
.reset-btn {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: transparent;
  font-weight: bold;
  font-size: 1.1rem;
  color: #b91c1c;
  border: none;
  box-shadow: none;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: transform 0.2s, box-shadow 0.2s;
}
.reset-btn:hover,
.reset-btn:active {
  transform: scale(1.08);
  box-shadow: 0 12px 40px #b91c1c88;
}
.reset-btn :deep(.el-icon-refresh) {
  margin-right: 6px;
  font-size: 1.2em;
}
.bottom-award-select-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 36px;
  display: flex;
  justify-content: center;
  z-index: 30;
  pointer-events: none;
}
.award-bg-select-wrapper {
  position: relative;
  width: 165px;
  height: 81px;
  display: flex;
  align-items: center;
  justify-content: center;
  pointer-events: auto;
}
.award-bg-img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  border-radius: 18px;
  box-shadow: 0 2px 12px #eab7a6aa;
  display: block;
}
.award-select-on-bg {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  min-width: 100px;
  max-width: 130px;
  width: 110px;
  font-size: 1.1rem;
  background: transparent;
  --el-select-input-height: 32px;
}
.award-select-on-bg :deep(.el-input__wrapper) {
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
  transition: transform 0.2s, box-shadow 0.2s;
}
.award-select-on-bg :deep(.el-input__wrapper:hover),
.award-select-on-bg :deep(.el-input__wrapper.is-focus),
.award-select-on-bg :deep(.el-input__wrapper:active) {
  transform: scale(1.08);
  box-shadow: 0 12px 40px #b91c1c88;
}
.award-select-on-bg :deep(.el-input__inner) {
  font-weight: bold;
  font-size: 1.1rem;
  color: #b91c1c !important;
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
}
.award-select-on-bg :deep(.el-select-dropdown__item) {
  font-weight: bold;
  font-size: 1.1rem;
  color: #b91c1c;
}
.award-select-on-bg :deep(.el-input__wrapper.is-focus),
.award-select-on-bg :deep(.el-input__wrapper:focus),
.award-select-on-bg :deep(.el-input__wrapper:active) {
  box-shadow: none !important;
  border-color: transparent !important;
  outline: none !important;
}
@keyframes rainbow-gradient-move {
  0% {
    background-position: 0% 50%;
  }
  100% {
    background-position: 100% 50%;
  }
}
.roller-num {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  /* 渐变色和字体大小由内联 style 控制 */
}
.roller-num-breath {
  animation: roller-num-breath 1.6s cubic-bezier(0.4,0,0.2,1) infinite alternate;
  text-shadow: 0 2px 12px #ffb3b3, 0 0 24px #e53935, 0 0 2px #fff;
}
@keyframes roller-num-breath {
  0% {
    transform: scale(1);
    text-shadow: 0 2px 12px #ffb3b3, 0 0 24px #e53935, 0 0 2px #fff;
  }
  50% {
    transform: scale(1.08);
    text-shadow: 0 6px 32px #fff700, 0 0 48px #e53935, 0 0 12px #fff;
  }
  100% {
    transform: scale(1);
    text-shadow: 0 2px 12px #ffb3b3, 0 0 24px #e53935, 0 0 2px #fff;
  }
}
.winner-marquee-wrap {
  width: 310px;
  height: 40px;
  overflow: hidden;
  margin: 0 auto 20px auto;
  border-radius: 5px;
  background: rgba(255,255,255,0.55);
  box-shadow: 0 0px 5px #FFFFFF;
  position: relative;
}
.winner-marquee-inner {
  display: flex;
  flex-direction: column;
}
.winner-content {
  height: 40px;
  line-height: 40px;
  font-size: 18px;
  color: #FFFFFF;
  text-align: center;
  font-weight: bold;
  letter-spacing: 1px;
  user-select: none;
}
.setting-btn {
  position: relative;
  font-weight: bold;
  font-size: 1.1rem;
  color: #6366f1;
  background: #fff;
  border: none;
  box-shadow: 0 2px 12px #6366f133;
  margin-left: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: transform 0.2s, box-shadow 0.2s;
}
.setting-btn:hover,
.setting-btn:active {
  transform: scale(1.08);
  box-shadow: 0 12px 40px #6366f188;
}
.setting-btn :deep(.el-icon) {
  margin-right: 6px;
  font-size: 1.2em;
}
.left-top-setting-btn {
  position: fixed;
  top: 44px;
  left: 24px;
  z-index: 200;
  background: #e53935 !important;
  color: #fff !important;
  border: none;
  box-shadow: 0 4px 16px #e5393533;
  width: 54px;
  height: 54px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.8rem;
  transition: transform 0.18s, box-shadow 0.18s;
  /* 不要有margin/padding，避免撑开父容器 */
  pointer-events: auto;
}
.left-top-setting-btn:hover {
  transform: scale(1.12) rotate(-10deg);
  box-shadow: 0 8px 32px #e5393588;
}
.left-top-setting-btn .el-icon {
  animation: setting-icon-rotate 2.5s linear infinite;
  animation-play-state: running;
  display: inline-block;
}
.left-top-setting-btn:hover .el-icon {
  animation-play-state: paused;
}
@keyframes setting-icon-rotate {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
.lottery-drawer-style {
  border-radius: 18px 0 0 18px !important;
  box-shadow: 0 8px 32px 0 #e5393533 !important;
  backdrop-filter: blur(12px);
  -webkit-backdrop-filter: blur(12px);
  border: 1px solid rgba(255,255,255,0.18);
}
.lottery-drawer-red {
  background: rgba(229,57,53,0.92) !important;
}
/* 金黄色标题和关闭按钮 */
.lottery-drawer-style .el-drawer__header {
  color: #FFD700 !important;
  border-bottom: 1.5px solid rgba(255,255,255,0.18);
  font-weight: bold;
}
.lottery-drawer-style .el-drawer__title {
  color: #FFD700 !important;
  font-weight: bold;
  font-size: 1.25rem;
}
.lottery-drawer-style .el-drawer__close-btn {
  color: #FFD700 !important;
  font-size: 1.5rem;
  transition: color 0.18s;
}
.lottery-drawer-style .el-drawer__close-btn:hover {
  color: #fff700 !important;
}
.drawer-save-btn {
  background: linear-gradient(90deg, #e53935, #ff1744) !important;
  color: #fff !important;
  border: none !important;
  border-radius: 12px !important;
  font-weight: bold;
  font-size: 1.1rem;
  box-shadow: 0 2px 12px #e5393533;
  padding: 0 28px;
  height: 40px;
  transition: transform 0.18s, box-shadow 0.18s;
}
.drawer-save-btn:hover,
.drawer-save-btn:active {
  transform: scale(1.08);
  box-shadow: 0 8px 32px #e5393588;
}
.drawer-cancel-btn {
  background: #fff !important;
  color: #e53935 !important;
  border: 1.5px solid #e53935 !important;
  border-radius: 12px !important;
  font-weight: bold;
  font-size: 1.1rem;
  box-shadow: 0 2px 12px #e5393533;
  padding: 0 28px;
  height: 40px;
  margin-right: 12px;
  transition: transform 0.18s, box-shadow 0.18s;
}
.drawer-cancel-btn:hover,
.drawer-cancel-btn:active {
  transform: scale(1.08);
  box-shadow: 0 8px 32px #e5393588;
}
.drawer-form-style {
  margin-top: 18px;
}
.drawer-form-wide .el-form-item {
  flex-wrap: nowrap;
  align-items: center;
}
.drawer-footer-btns {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  padding: 0 8px 8px 8px;
}
.drawer-title-animate {
  text-align: center;
  font-size: 2.1rem;
  font-weight: bold;
  color: #e53935;
  text-shadow: 0 2px 12px #ffb3b3, 0 0 24px #e53935, 0 0 2px #fff;
  letter-spacing: 4px;
  margin-bottom: 0.5em;
  margin-top: 2px;
  flex: 1;
  transition: none;
  animation: drawer-title-bounce-glow 1.6s cubic-bezier(0.4,0,0.2,1) infinite alternate;
  cursor: default;
}
@keyframes drawer-title-bounce-glow {
  0% {
    transform: translateY(0) scale(1);
    text-shadow: 0 2px 12px #ffb3b3, 0 0 24px #e53935, 0 0 2px #fff;
  }
  50% {
    transform: translateY(-6px) scale(1.06);
    text-shadow: 0 6px 32px #fff700, 0 0 48px #e53935, 0 0 12px #fff;
  }
  100% {
    transform: translateY(0) scale(1);
    text-shadow: 0 2px 12px #ffb3b3, 0 0 24px #e53935, 0 0 2px #fff;
  }
}
.drawer-x-btn {
  position: absolute;
  top: 50%;
  right: 0.2em;
  transform: translateY(-50%);
  background: transparent;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 0;
  margin: 0;
  z-index: 2;
  display: flex;
  align-items: center;
  transition: none;
}
.drawer-x-icon {
  color: #e53935;
  filter: drop-shadow(0 2px 8px #ffb3b3);
  transition: none;
}
/* 只让关闭按钮的X有hover动画，其他按钮不受影响 */
.drawer-x-btn:hover .drawer-x-icon {
  transform: scale(1.18);
  filter: drop-shadow(0 4px 16px #e53935) drop-shadow(0 0 8px #fff700);
}
/* 删除.drawer-title-animate:hover和.drawer-header-flex:hover的hover动画样式，避免影响其他按钮 */
.drawer-header-flex {
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  width: 100%;
  min-height: 48px;
}
.drawer-x-btn {
  position: absolute;
  top: 50%;
  right: 0.2em;
  transform: translateY(-50%);
  background: transparent;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 0;
  margin: 0;
  z-index: 2;
  display: flex;
  align-items: center;
  transition: none;
}
.drawer-x-icon {
  color: #e53935;
  filter: drop-shadow(0 2px 8px #ffb3b3);
  transition: none;
}
.lottery-btn-breath {
  animation: lottery-btn-breath 1.7s cubic-bezier(0.4,0,0.2,1) infinite alternate;
}
@keyframes lottery-btn-breath {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.08);
  }
  100% {
    transform: scale(1);
  }
}
.breath-animate {
  animation-play-state: running;
}
.breath-animate:hover {
  animation-play-state: paused !important;
}
@media (max-width: 900px) {
  .absolute-left-card {
    position: static;
    transform: none;
    margin: 32px auto 0 auto;
    min-width: 90vw;
    max-width: 98vw;
    min-height: 120px;
    padding: 20px 10px;
  }
  .lottery-main-content-center {
    margin: 0 auto;
    width: 100%;
    padding-top: 32px;
  }
  .top-right-reset {
    top: 12px;
    right: 8px;
  }
  .reset-bg-img {
    width: 110px;
    height: 54px;
  }
  .fixed-lottery-btn {
    width: 80px;
    height: 80px;
    right: 16px;
    bottom: 16px;
  }
  .award-bg-select-wrapper {
    width: 70px;
    height: 36px;
    margin-left: 8px;
  }
  .award-select-on-bg {
    min-width: 60px;
  }
}
@media (max-width: 600px) {
  .lucky-title-space {
    height: 4vh;
  }
  .lucky-title-img {
    width: 90vw;
    max-width: 98vw;
    margin-left: auto;
    margin-right: auto;
  margin-bottom: 20px;
}
  .rects-row {
    gap: 32px;
    margin-top: 40px;
  }
  .rect-img {
    width: 100px;
    height: 100px;
  }
  .fixed-lottery-btn {
    width: 80px;
    height: 80px;
    right: 28px;
    bottom: 28px;
  }
  .lottery-main-content-center {
    padding-top: 16px;
  }
  .award-bg-select-wrapper {
    width: 110px;
    height: 54px;
  }
  .award-bg-img {
    width: 110px;
    height: 54px;
  }
  .award-select-on-bg {
    min-width: 70px;
    max-width: 90px;
    width: 80px;
    font-size: 0.95rem;
  }
}
.award-winner-list {
  width: 100%;
  margin: 48px auto 0 auto;
  display: flex;
  flex-wrap: wrap;
  gap: 32px;
  justify-content: center;
}
.award-winner-card {
  min-width: 220px;
  max-width: 320px;
  background: rgba(255,255,255,0.7);
  border-radius: 18px;
  box-shadow: 0 4px 18px #e5393533;
  padding: 18px 24px 14px 24px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
.award-title {
  font-size: 1.25rem;
  font-weight: bold;
  margin-bottom: 10px;
  letter-spacing: 2px;
  color: #e53935;
  text-shadow: 0 2px 8px #ffb3b3;
}
.award-title.special {
  color: #FFD700;
  text-shadow: 0 2px 12px #fff700, 0 0 8px #e53935;
}
.award-title.first {
  color: #e53935;
}
.award-title.second {
  color: #b91c1c;
}
.award-title.third {
  color: #6366f1;
}
.award-title.lucky {
  color: #21d4fd;
  text-shadow: 0 2px 12px #21d4fd, 0 0 8px #b721ff;
}
.award-list {
  padding-left: 18px;
  margin: 0;
  color: #333;
  font-size: 1.08rem;
}
.award-list li {
  margin-bottom: 4px;
  line-height: 1.7;
}
.winner-award-list {
  width: 310px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.winner-award-item {
  background: rgba(255,255,255,0.55);
  border-radius: 10px;
  box-shadow: 0 2px 8px #e5393533;
  padding: 6px 10px 6px 10px;
  margin-bottom: 5px;
  height: 140px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  position: relative;
}
.award-title {
  position: absolute;
  top: 10px;
  left: 18px;
  font-size: 1.18rem;
  font-weight: bold;
  margin: 0;
  z-index: 2;
  color: #e53935;
  letter-spacing: 2px;
}

.award-remaining {
  position: absolute;
  top: 10px;
  right: 18px;
  font-size: 0.9rem;
  color: #666;
  font-weight: 500;
  z-index: 2;
}
.award-number-list {
  margin-top: 48px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  max-height: 140px;
  overflow-y: auto;
  overflow-x: hidden;
  padding-right: 2px;
  align-items: center;
  justify-content: center;
}
.award-number-list::-webkit-scrollbar {
  width: 5px;
  background: transparent;
}
.award-number-list::-webkit-scrollbar-thumb {
  background: #e53935;
  border-radius: 2px;
}
.number-badge {
  display: inline-block;
  min-width: 48px;

  border: 3px solid #e53935;
  border-radius: 5px;
  background: #fff;
  color: #e53935;
  font-weight: bold;
  font-size: 1.2rem;
  text-align: center;
  box-shadow: 0 2px 8px #e5393533;
  letter-spacing: 2px;
  transition: border 0.3s;
  box-sizing: border-box;
}
.winner-award-item .award-list {
  display: inline;
  padding-left: 0;
  margin: 0;
  color: #b91c1c;
  font-size: 1rem;
}
.winner-award-item .award-list li {
  display: inline;
  margin-right: 10px;
  line-height: 1.6;
  list-style: none;
}

.flying-badge {
  z-index: 99999;
  pointer-events: none;
  position: fixed;
  background: #fff;
  color: #e53935;
  border: 2px solid #e53935;
  border-radius: 5px;
  box-shadow: 0 2px 8px #e5393533;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  font-weight: bold;
  letter-spacing: 2px;
}
.winner-msg-number {
  color: #fff !important;
  font-weight: 900;
  font-size: 1.5rem;
}
.winner-msg-award {
  font-weight: 900;
  font-size: 1.5rem;
}
.winner-msg-award.special {
  color: #FFD700 !important;
}
.winner-msg-award.first {
  color: #e53935 !important;
}
.winner-msg-award.second {
  color: #b91c1c !important;
}
.winner-msg-award.third {
  color: #6366f1 !important;
}
.winner-msg-award.lucky {
  color: #21d4fd !important;
}
.winner-msg-gradient {
  color: #b91c1c;
  font-weight: bold;
  font-size: 1.4rem;
  background: none !important;
  -webkit-background-clip: unset !important;
  -webkit-text-fill-color: unset !important;
  background-clip: unset !important;
  text-fill-color: unset !important;
  animation: none !important;
}
.no-winner {
  color: #5e5a5a;
  font-size: 1.1rem;
  font-style: italic;
  width: 100%;
  text-align: center;
  margin: 0;
}
</style>
